﻿using System;
using System.Collections.Generic;
using AutoMapper;
using VMWorkshop.Domain;

namespace VMWorkshop.WinForms.Models.ViewModels
{
    class DemoViewModel
    {
        // Private fields
        private IList<ProductListView> _products;
        private IProductRepository _repository;

        // Public properties
        public bool IsEditFormVisible {get;set;}
        public bool IsUpdateMessageVisible {get;set;}

        public IList<ProductListView> Products
        {
            get 
            {
                if (this._products == null)
                {
                    this._products = this.GetProducts();
                }
                return this._products; 
            }
            set { this._products = value;}
        }

        public ProductEditView SelectedProduct {get;set;}

        // Constructor
        public DemoViewModel(IProductRepository repository)
        {
            this._repository = repository;
            this.ClearSelectedProduct();
        }

        // Public API methods
        public void Persist()
        {
            Product newProduct = ProductEditView.ToProduct(this.SelectedProduct);
            Product oldProduct = this._repository.GetProductById(newProduct.ProductId);
            oldProduct = Mapper.Map<Product, Product>(newProduct, oldProduct);
            this._repository.Persist(oldProduct);

            this.IsEditFormVisible = false;
            this.IsUpdateMessageVisible = true;
        }

        public void GetSelectedProduct(string productId)
        {
            int num;

            if (int.TryParse(productId, out num))
            {
                this.GetSelectedProduct(num);
            }
            else
            {
                throw new ApplicationException("Invalid integer value for ProductId");
            }
        }

        public void GetSelectedProduct(int productId)
        {
            Product product = this._repository.GetProductById(productId);
            this.SelectedProduct = ProductEditView.ToProductEditView(product);

            this.IsEditFormVisible = true;
            this.IsUpdateMessageVisible = false;
        }

        // Utilities
        private IList<ProductListView> GetProducts()
        {
            var products = this._repository.GetAll();
            return Mapper.Map<IList<Product>, IList<ProductListView>>(products);
        }

        private void ClearSelectedProduct()
        {
            this.SelectedProduct = new ProductEditView();
        }
    }
}
